
import { CheckCircleTwoTone, CloseOutlined, FileSearchOutlined, FolderOutlined, HomeOutlined, PlusOutlined, SendOutlined } from '@ant-design/icons';
import { FormListActionType, ModalForm, ProCard, ProFormDatePicker, ProFormGroup, ProFormList, ProFormTextArea } from '@ant-design/pro-components';
import ProForm, {
    DrawerForm,
    ProFormDateTimeRangePicker,
    ProFormInstance,
    ProFormSelect,
    ProFormText,
} from '@ant-design/pro-form';
import ProList from '@ant-design/pro-list';
import ProTable, { ActionType } from '@ant-design/pro-table';
import { log } from '@antv/g2plot/lib/utils';
import { useAccess } from '@umijs/max';
import { Button, Divider, Empty, Space, message } from 'antd';
import Tree, { DataNode } from 'antd/es/tree';
import moment from 'moment';
import React, { useRef, useState } from 'react';
import AddNewsPreview from './AddNewsPreview';

interface AddNewsProps {
    onRefurbish: (id: string) => void;
}

const AddNews: React.FC<AddNewsProps> = ({ onRefurbish }) => {
    const access = useAccess();
    // const actionRef = useRef<ActionType>();
    const actionRef = useRef<
        FormListActionType<{
            name: string;
        }>
    >();
    const formRef = useRef<ProFormInstance>();
    const [openAddNewsPreview, setOpenAddNewsPreview] = useState<boolean>(false);
    const [previewData, setPreviewData] = useState<NewsData.PageResult[]>();
    const [modalFormOpen, setModalFormOpenState] = useState<boolean>(false);
    return (
        <DrawerForm
            key="add_promotion_task_drawer_form_douyin"
            title="添加要情"
            drawerProps={{
                maskClosable: false,
                destroyOnClose: true,
            }}
            formRef={formRef}
            trigger={
                <Button key="create" type="primary">
                    <PlusOutlined />
                    添加要情
                </Button>
            }
            submitter={{
                searchConfig: {
                    submitText: (
                        <>
                            <FileSearchOutlined /> 预览
                        </>
                    ),
                },
                render: (props, defaultDoms) => {
                    return [
                        defaultDoms,
                        <AddNewsPreview
                            key="add_active_preview"
                            onSubmit={() => {
                                // setOpenAddActive(false);
                                // setOpen(true)
                                // onRefurbish();
                            }}
                            open={openAddNewsPreview}
                            onOpenChange={(open) => {
                                setOpenAddNewsPreview(open);
                            }}
                            details={previewData}
                        />,
                        <Button
                            key="button_add_submit"
                            icon={<SendOutlined />}
                            type="primary"
                            style={{
                                background: '#87d068',
                            }}
                            onClick={() => {
                                /**
                                 * ======================
                                 * 直接发布
                                 * ======================
                                 */
                                const values = formRef.current?.getFieldsValue();

                                if (!(values.articleName !== undefined && values.articleName.length > 0)) {
                                    message.warning('请输入标题');
                                    return;
                                }

                                if (
                                    !(values.articleIndustryIds !== undefined && values.articleIndustryIds.length > 0)
                                ) {
                                    message.warning('请选择至少一个选题方向');
                                    return;
                                }

                                if (!(values.articleLabels !== undefined && values.articleLabels.length > 0)) {
                                    message.warning('请输入至少一个标签');
                                    return;
                                }

                                if (!(values.articleContent !== undefined && values.articleContent.length > 0)) {
                                    message.warning('请输入内容');
                                    return;
                                }

                                setModalFormOpenState(true);
                            }}
                        >
                            提交
                        </Button>,
                        <ModalForm
                            key={'modal_form_add_submit'}
                            title={
                                <>
                                    <CheckCircleTwoTone
                                        style={{
                                            marginRight: 8,
                                        }}
                                        twoToneColor="#87d068"
                                    />
                                    确认提交
                                </>
                            }
                            autoFocusFirstInput
                            modalProps={{
                                width: 400,
                                destroyOnClose: true,
                            }}
                            open={modalFormOpen}
                            onOpenChange={setModalFormOpenState}
                            submitTimeout={2000}
                            submitter={{
                                submitButtonProps: {
                                    type: 'primary',
                                    style: { background: '#87d068' },
                                },
                            }}
                            onFinish={async () => {
                                const values = formRef.current?.getFieldsValue();

                                if (
                                    values.articleAttachments !== undefined &&
                                    values.articleAttachments.length > 0
                                ) {
                                    const articleAttachments = values.articleAttachments.map(
                                        (item: { response: { data: { id: any } } }) => {
                                            return item.response.data.id;
                                        },
                                    );

                                    values.articleAttachments = articleAttachments;
                                }

                                // const response = await saveCuesActive({
                                //     articleName: values?.articleName,
                                //     articleIndustryIds: values?.articleIndustryIds,
                                //     articleLabels: values?.articleLabels,
                                //     remarks: values?.remarks,
                                //     assignOrganizationIds: values?.assignOrganizationIds,
                                //     articleContent: values?.articleContent,
                                //     articleAttachments: values.articleAttachments,
                                //     createdSource: 1,
                                // });

                                // if (response.code === 0) {
                                //     message.success('提交成功');
                                //     setOpenAddActive(false);
                                //     setOpen(true)
                                //     onRefurbish();
                                //     return true;
                                // } else {
                                //     return false;
                                // }
                            }}
                        />,
                    ];
                },
            }}
            initialValues={{
                isDemandClipboard: 1,
            }}
            onOpenChange={(visible: boolean) => {
                if (visible) {
                    //加载权限树请求网络
                }
            }}
            onValuesChange={(values) => {
                console.log('=====', values);
            }}
            onFinish={async (values) => {
                console.log(values, actionRef.current?.getList(),);
                setPreviewData(actionRef.current?.getList())
                setOpenAddNewsPreview(true);
            }}
        >
            <ProForm.Group>
                {/* <ProFormText
                    width="xl"
                    name="title"
                    label="标题"
                    rules={[{ required: true, message: '请输入标题' }]}
                    fieldProps={{
                        allowClear: true,
                        maxLength: 200,
                    }}
                />
                <ProFormText
                    width="xl"
                    name="content"
                    label="内容"
                    rules={[{ required: true, message: '请输入标题' }]}
                    fieldProps={{
                        allowClear: true,
                        maxLength: 200,
                    }}
                /> */}
                <ProFormDatePicker
                    rules={[{ required: true, message: '这是必填项' }]}
                    width="xl"
                    name="time"
                    label="要情发布时间"
                    tooltip="时间"
                />
            </ProForm.Group>
            <Divider orientation="left" plain>
                添加要情
            </Divider>
            <div style={{ textAlign: 'right' }}>
                <Space align="center">
                    <Button
                        key="add_topic_plan"
                        size="small"
                        type="primary"
                        onClick={() => {

                            const list = actionRef.current?.getList();
                            actionRef.current?.add({
                                name: '要情' + (Number(list?.length) + 1),
                            });
                        }}
                    >
                        创建
                    </Button>
                </Space>
            </div>
            <ProForm onFinish={async (e) => console.log(e)} submitter={false} >
                <ProFormList
                    creatorButtonProps={false}
                    name="users"
                    label="要情信息"
                    initialValue={[
                        {
                            name: "要情" + '1',
                        },
                    ]}
                    creatorRecord={{
                        name: '222',
                    }}
                    copyIconProps={false}
                    actionGuard={{
                        beforeAddRow: async (defaultValue, insertIndex) => {
                            return new Promise((resolve) => {
                                console.log(defaultValue, insertIndex);
                                setTimeout(() => resolve(true), 1000);
                            });
                        },
                        beforeRemoveRow: async (index) => {
                            return new Promise((resolve) => {
                                if (index === 0) {
                                    message.error('至少添加一个要情');
                                    resolve(false);
                                    return;
                                }
                                setTimeout(() => resolve(true), 1000);
                            });
                        },
                    }}
                    itemRender={({ listDom, action }, { record }) => {
                        return (
                            <ProCard
                                bordered
                                extra={action}
                                title={record?.name}
                                style={{
                                    marginBlockEnd: 8,
                                }}
                            >
                                {listDom}
                            </ProCard>
                        );
                    }}
                    actionRef={actionRef}

                >
                    <ProFormText
                        rules={[{ required: true, message: '这是必填项' }]}
                        name="title"
                        label="标题"
                    />
                    <ProFormText
                        rules={[{ required: true, message: '这是必填项' }]}
                        name="datasource"
                        label="数据渠道"
                    />
                    <ProFormDatePicker
                        rules={[{ required: true, message: '这是必填项' }]}
                        width="xl"
                        name="pubtime"
                        label="发布日期"
                        tooltip="发布时间"
                    />
                    <ProFormText
                        rules={[{ required: true, message: '这是必填项' }]}
                        name="sourceUrl"
                        label="文章原文链接"
                    />
                    <ProFormTextArea
                        name="content"
                        label="文章内容"
                        rules={[{ required: true, message: '这是必填项' }]}
                        fieldProps={{
                            allowClear: true,
                            rows: 3,
                            maxLength: 200,
                        }}
                    />

                </ProFormList>
            </ProForm>
        </DrawerForm>
    );
};
export default AddNews;
